//
//  YWMeterReadingManager.m
//  maintain
//
//  Created by 郑想 on 16/2/26.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "MJExtension.h"
#import "YWMacro.h"
#import "WMHttpTool.h"
#import "YWLoginTool.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWCommonTool.h"
#import "YWDBTool.h"
#import "YWMeterReadingManager.h"
#import "YWResourceManager.h"
#import "YWThisMonthReadingMeterCount.h"
#import "YWEquipmentManager.h"
#import "YWMeterReadingDBManager.h"
#import "YWLogRecordTool.h"
#import "YWConst.h"
#import <Bugly/Bugly.h>

#define kThisMonthReadMeterCountPlistPath [[NSBundle mainBundle] pathForResource:@"thisMonthReadMeterCount" ofType:@"plist"]

static BOOL isUploading = NO;

@interface YWMeterReadingManager ()
@property (nonatomic, strong) dispatch_group_t group;
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
//@property (nonatomic, strong) dispatch_semaphore_t signal;

@property (nonatomic, assign) NSInteger waterMeterEquipmentTypeId;
@property (nonatomic, assign) NSInteger electricMeterEquipmentTypeId;
@property (nonatomic, assign) NSInteger gasMeterEquipmentTypeId;
@end
@implementation YWMeterReadingManager
YWSingletonM(Manager)

- (dispatch_group_t)group{
    if (!_group) {
        _group = dispatch_group_create();
    }
    return _group;
}

//- (dispatch_queue_t)serialQueue
//{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("uploadMeterReadingRecordserialQueue", DISPATCH_QUEUE_SERIAL); //创建上传串行队列
//    }
//    return _serialQueue;
//}
//
//- (dispatch_semaphore_t)signal{
//    if (!_signal) {
//        _signal = dispatch_semaphore_create(1);
//    }
//    return _signal;
//}

- (NSInteger)waterMeterEquipmentTypeId
{
    if (!_waterMeterEquipmentTypeId) {
        _waterMeterEquipmentTypeId = [[YWDBTool shareDBTool]equipmentTypeIdWithOwnCode:@"Water_Meter"];
    }
    return _waterMeterEquipmentTypeId;
}

- (NSInteger)electricMeterEquipmentTypeId{
    if (!_electricMeterEquipmentTypeId) {
        _electricMeterEquipmentTypeId = [[YWDBTool shareDBTool]equipmentTypeIdWithOwnCode:@"Electric_Meter"];
    }
    return _electricMeterEquipmentTypeId;
}

- (NSInteger)gasMeterEquipmentTypeId{
    if (!_gasMeterEquipmentTypeId) {
        _gasMeterEquipmentTypeId = [[YWDBTool shareDBTool]equipmentTypeIdWithOwnCode:@"Gas_Meter"];
    }
    return _gasMeterEquipmentTypeId;
}

- (YWEquipment*)meterNumber:(NSString*)ownCode
{
    YWEquipment* equipment = [[YWDBTool shareDBTool] equipmentWithOwncode:ownCode];
    if (equipment) {
        if (equipment.equipmentTypeId == [self waterMeterEquipmentTypeId] || equipment.equipmentTypeId == [self electricMeterEquipmentTypeId] || equipment.equipmentTypeId == [self gasMeterEquipmentTypeId]) {
            return equipment;
        }
    }
    return nil;
}

- (YWEquipment*)meterQRCoder:(NSString*)qrCode
{
    NSArray* equipments = [[YWDBTool shareDBTool] equipmentWithQrcodeId:qrCode];
    for (YWEquipment* equipment in equipments) {
        if (equipment.equipmentTypeId == [self waterMeterEquipmentTypeId] || equipment.equipmentTypeId == [self electricMeterEquipmentTypeId] || equipment.equipmentTypeId == [self gasMeterEquipmentTypeId]) {
            return equipment;
        }
    }
    return nil;
}

- (void)requestNewestReadingMemterRecord:(NSString*)equipmentId complete:(YWNewestReadingCompleteBlock)block
{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (block) {block(nil);}return;}
    NSDictionary* params = @{ @"equipmentId" : equipmentId };
    NSString *url = [YWCommonTool getNewestReadingMemterRecordUrl];
    YWLog(@"最近水电抄表记录url:%@,params:%@",url,params);
    
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        YWMeterReadingRecord* meterReadingRecord = [YWMeterReadingRecord mj_objectWithKeyValues:json];
        if (meterReadingRecord) {
            [self saveMeterReadingRecords:@[meterReadingRecord]];
            if (block) {
                block(meterReadingRecord);
            }
        }else{
            if (block) {
                block(nil);
            }
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (block) {
            block(nil);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (BOOL)updatePatrolPictureWithArray:(NSArray*)patrolPictures
{
    return [[YWDBTool shareDBTool] updatePatrolPictureWithArray:patrolPictures];
}

- (BOOL)updatePatrolPictureRecordId:(NSString*)recordId WithOldRecordId:(NSString*)ordRecordId
{
    return [[YWDBTool shareDBTool] updatePatrolPictureRecordId:recordId WithOldRecordId:ordRecordId];
}

- (NSArray*)recordPictureWithRecordId:(NSString*)recordId recordType:(YWPictureRecordType)recordType
{
    return [[YWDBTool shareDBTool] recordPictureWithRecordId:recordId recordType:recordType];
}

- (BOOL)updateMeterReadingRecordWithRecordArray:(NSArray*)records{
    return [[YWMeterReadingDBManager shareManager] updateMeterReadingRecordWithRecordArray:records];
}

- (BOOL)updateMeterReadingRecordWithRecord:(YWMeterReadingRecord*)record
{
    return [[YWMeterReadingDBManager shareManager] updateMeterReadingRecordWithRecord:record];
}

- (NSArray*)meterReadingRecordWithEquipmentType:(NSInteger)meterEquipmentType page:(NSInteger)page
{
    return [[YWMeterReadingDBManager shareManager] meterReadingRecordWithEquipmentType:meterEquipmentType page:page];
}

- (YWMeterReadingRecord*)meterReadingRecordWithRecordId:(NSString*)recordId{
    return [[YWMeterReadingDBManager shareManager] meterReadingRecordWithRecordId:recordId];
}

- (YWMeterReadingRecord *)latestMeterReadingRecordWithEquipmentId:(NSString *)equipmentId{
    return [[YWMeterReadingDBManager shareManager] latestMeterReadingRecordWithEquipmentId:equipmentId];
}

- (BOOL)modifyMeterReadingRecordIdWithRecord:(YWMeterReadingRecord*)record recordId:(NSString*)recordId
{
    return [[YWMeterReadingDBManager shareManager] modifyMeterReadingRecordIdWithRecord:record recordId:recordId];
}

- (BOOL)updateMeterReadingRecordUploadStatus:(YWMeterReadingRecordUploadStatus)uploadStatus recordId:(NSString*)recordId
{
    return [[YWMeterReadingDBManager shareManager] updateMeterReadingRecordUploadStatus:uploadStatus recordId:recordId];
}

- (BOOL)deleteMeterReadingRecordWithEquipmentType:(NSInteger)meterEquipmentType{
    return [[YWMeterReadingDBManager shareManager] deleteMeterReadingRecordWithEquipmentType:meterEquipmentType];
}

- (NSArray*)meterReadingRecordWithUploadStatusFail
{
    return [[YWMeterReadingDBManager shareManager] meterReadingRecordWithUploadStatusFail];
}

- (void)uploadFailMeterReadingRecords{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (![YWLoginTool isLogin]) {
            return;
        }
        if (isUploading == YES) {
            return;
        }
        isUploading = YES;
        
        NSArray* uploadFailMeterReadingRecords = [self meterReadingRecordWithUploadStatusFail];
        [uploadFailMeterReadingRecords enumerateObjectsUsingBlock:^(YWMeterReadingRecord* _Nonnull meterReadingRecord, NSUInteger idx, BOOL* _Nonnull stop) {
            NSArray* pictures = [self recordPictureWithRecordId:meterReadingRecord.meterRecordId recordType:YWPictureRecordTypeMeterReading];
            
            dispatch_group_enter(self.group);
            if (pictures.count>0) {
                [[YWResourceManager shareManager] uploadPatrolPictureToAliyunOSS:pictures complete:^(BOOL isError, NSArray* uploadPictures) {
                    [self uploadCompleteHandleWithRecords:@[ meterReadingRecord ] uploadPictures:uploadPictures error:isError];
                }];
            }else{
                [self uploadCompleteHandleWithRecords:@[ meterReadingRecord ] uploadPictures:nil error:NO];
            }
            dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
            
            if (idx == uploadFailMeterReadingRecords.count-1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPushBackgroundUploadRecordSuccessNotification object:nil];
                });
            }
        }];
        
        isUploading = NO;
    });
    
}

- (void)startUploadMeterReadingRecords:(NSArray*)records pictures:(NSArray*)pictures{
    if (records.count == 0) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_group_enter(self.group);
        if (pictures.count>0) {
            [[YWResourceManager shareManager] uploadPatrolPictureToAliyunOSS:pictures complete:^(BOOL isError, NSArray* uploadPictures) {
                [self uploadCompleteHandleWithRecords:records uploadPictures:uploadPictures error:isError];
            }];
        }else{
            [self uploadCompleteHandleWithRecords:records uploadPictures:nil error:NO];
        }
        dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
    });
}


- (void)uploadCompleteHandleWithRecords:(NSArray*)records uploadPictures:(NSArray*)uploadPictures error:(BOOL)isError{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self updatePatrolPictureWithArray:uploadPictures];
        if (!isError) {
            [self submitMeterReadingRequestWithRecords:records Pictures:uploadPictures];
        }else {
            [records enumerateObjectsUsingBlock:^(YWMeterReadingRecord* _Nonnull meterReadingRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                [self updateMeterReadingRecordUploadStatus:YWMeterReadingRecordUploadStatusUnFinished recordId:meterReadingRecord.meterRecordId];
            }];
            dispatch_group_leave(self.group);
        }
    });
}

- (void)submitMeterReadingRequestWithRecords:(NSArray*)records Pictures:(NSArray*)pictures
{
    NSDictionary *headers = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headers;
    if (headers == nil) {dispatch_group_leave(self.group);return;}
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    [records enumerateObjectsUsingBlock:^(YWMeterReadingRecord* _Nonnull meterReadingRecord, NSUInteger idx, BOOL* _Nonnull stop) {
        [params setObject:meterReadingRecord.equipmentId?:@"" forKey:@"equipment.equipmentId"];
        NSString *thisReadStr = [NSString stringWithFormat:@"%.1f",meterReadingRecord.thisReadNumber];
        [params setObject:thisReadStr?:@"" forKey:@"reading"];
        [params setObject:meterReadingRecord.readingMonth?:@"" forKey:@"readingMonth"];
        [params setObject:meterReadingRecord.note?:@"" forKey:@"note"];
        [params setObject:meterReadingRecord.uniqueTag?:@"" forKey:@"uniqueTag"];

        [pictures enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull picture, NSUInteger index, BOOL* _Nonnull stop) {
            [params setObject:picture.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].url", (unsigned long)index]];
            [params setObject:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].thumbnailUrl", (unsigned long)index]];
            [params setObject:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].previewUrl", (unsigned long)index]];
        }];
    }];
    NSString *url = [YWCommonTool getSubmitMeterReadingRecordUrl];
    YWLog(@"提交抄表记url:%@,params:%@",url,params);
    //保存请求前的参数日志
    NSString *logTag = [YWCommonTool randStringId];
    NSMutableDictionary * logDic = [[YWLogRecordTool shareLogRecordManager] getLogDictionaryWithModule:@"抄表" interface:url params:params headers:headers tag:logTag];
    [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:logDic];
    
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [records enumerateObjectsUsingBlock:^(YWMeterReadingRecord* _Nonnull meterReadingRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                [self updateMeterReadingRecordUploadStatus:YWMeterReadingRecordUploadStatusFinished recordId:meterReadingRecord.meterRecordId];
                YWMeterReadingRecord* successRecord = [YWMeterReadingRecord mj_objectWithKeyValues:json];
                
                if (successRecord.meterRecordId.length>0) {
                    BOOL success = [self modifyMeterReadingRecordIdWithRecord:meterReadingRecord recordId:successRecord.meterRecordId];
                    if (success) {
                        for (YWPatrolPicture* picture in pictures) {
                            picture.recordId = [NSString stringWithFormat:@"%@", successRecord.meterRecordId];
                        }
                        [self updatePatrolPictureWithArray:pictures];
                        if (meterReadingRecord) {
                            meterReadingRecord.meterRecordId = successRecord.meterRecordId;
                            meterReadingRecord.uploadStatus = YWMeterReadingRecordUploadStatusFinished;
                            [[YWMeterReadingDBManager shareManager] updateNetWorkMeterReadingRecordWithRecordArray:@[meterReadingRecord]];
                        }
                    }
                }
            }];
            //保存请求成功的参数日志
            NSMutableDictionary * successDic =
            [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:@"无" logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:successDic];
            
            dispatch_group_leave(self.group);
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
            //保存请求失败的参数日志
            NSString * result = [NSString stringWithFormat:@"%s,error:%@", __func__, error.localizedDescription];
            NSMutableDictionary * failedDic = [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:result logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:failedDic];
            
            if (response.statusCode == 405 || response.statusCode == 412) {
                //405读数不可小于前一次抄表读数,412读数不可大于后一次抄表读数
                [records enumerateObjectsUsingBlock:^(YWMeterReadingRecord* _Nonnull meterReadingRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                    //YWMeterReadingRecordUploadStatusNull这个状态不会被离线上传
                    [self updateMeterReadingRecordUploadStatus:YWMeterReadingRecordUploadStatusNull recordId:meterReadingRecord.meterRecordId];
                }];
            }else{
                //上传错误参数
                if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                    NSString *statusCode = [NSString stringWithFormat:@"statusCode: %@",@(response.statusCode).stringValue];
                    [Bugly reportException:[NSException exceptionWithName:@"抄表接口错误" reason:statusCode userInfo:params]];
                }
                
                [records enumerateObjectsUsingBlock:^(YWMeterReadingRecord* _Nonnull meterReadingRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                    //更新上传状态
                    [self updateMeterReadingRecordUploadStatus:YWMeterReadingRecordUploadStatusUnFinished recordId:meterReadingRecord.meterRecordId];
                }];
            }
            dispatch_group_leave(self.group);
        });
    }];
}

- (NSArray*)allThisMonthReadMeterCount:(NSInteger)equipmenttypeId;
{
    return [[YWMeterReadingDBManager shareManager] allThisMonthReadMeterCount:equipmenttypeId];
}

- (NSInteger)toDayReadMeterCountWithEquipmentTypeId:(NSInteger)equipmentTypeId
{
    return [[YWMeterReadingDBManager shareManager] toDayReadMeterCountWithEquipmentTypeId:equipmentTypeId];
}

- (void)requestThisMonthReadingMeterCount:(void (^)(BOOL success))complete
{
    NSString* buildingIds = [[YWBuildingManager shareManager] allBuildingId];
    if (buildingIds) {
        NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
        [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
        if (headersDic == nil) {if (complete) {complete(NO);}return;}
        NSDictionary* params = @{ @"buildingIds" : buildingIds };
        NSString *url = [YWCommonTool getThisMonthReadMeterCountUrl];
        YWLog(@"获取楼盘当月已抄表数量url:%@,params:%@",url,params);
        
        [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
            NSArray* thisMonthReadingMeterCountJsons = [YWThisMonthReadingMeterCountJson mj_objectArrayWithKeyValuesArray:json];
            if (thisMonthReadingMeterCountJsons) {
                [[YWMeterReadingDBManager shareManager] saveThisMonthReadMeterCountWithJson:thisMonthReadingMeterCountJsons];
            }
            if (complete) {
                complete(YES);
            }
        } failure:^(NSHTTPURLResponse* response, NSError* error) {
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
            if (complete) {
                complete(NO);
            }
        }];
    }
}

- (void)requestMyMeterReadingRecordsWithEquipmentTypeOwnCode:(NSString *)equipmentTypeOwnCode page:(NSInteger)page pageSize:(NSInteger)pageSize Block:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:equipmentTypeOwnCode forKey:@"equipmentTypeOwnCode"];
    [params setValue:@(pageSize) forKey:@"pageSize"];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    NSString *url = [YWCommonTool getMyMeterReadingRecordUrl];
    YWLog(@"获取我的抄表记录url:%@,params:%@",url,params);
    
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        if (page == 1) {
            NSInteger wEquipmentTypeId = 0;
            if ([equipmentTypeOwnCode isEqualToString:@"Water_Meter"]) {
                wEquipmentTypeId = [[YWMeterReadingManager shareManager]waterMeterEquipmentTypeId];
                [self deleteMeterReadingRecordWithEquipmentType:wEquipmentTypeId];
            }else if ([equipmentTypeOwnCode isEqualToString:@"Electric_Meter"]){
                wEquipmentTypeId = [[YWMeterReadingManager shareManager]electricMeterEquipmentTypeId];
                [self deleteMeterReadingRecordWithEquipmentType:wEquipmentTypeId];
            }else if ([equipmentTypeOwnCode isEqualToString:@"Gas_Meter"]){
                wEquipmentTypeId = [[YWMeterReadingManager shareManager]gasMeterEquipmentTypeId];
                [self deleteMeterReadingRecordWithEquipmentType:wEquipmentTypeId];
            }
        }
        
        NSArray* myMeterReadingRecords = [YWMeterReadingRecord mj_objectArrayWithKeyValuesArray:json];
        if (myMeterReadingRecords.count) {
            [self saveMeterReadingRecords:myMeterReadingRecords];
        }
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:@"请求失败,稍后请重试"];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        
    }];
}


- (BOOL)saveMeterReadingRecords:(NSArray*)records{
    BOOL isSave = YES;
    [records enumerateObjectsUsingBlock:^(YWMeterReadingRecord*  _Nonnull record, NSUInteger idx, BOOL * _Nonnull stop) {
        record.uploadStatus = YWMeterReadingRecordUploadStatusFinished;
        NSString* yearMonth = [YWCommonTool showTime:record.readingTime / 1000 andFormatter:KTimeFormatYearMonth];
        yearMonth = [yearMonth stringByReplacingOccurrencesOfString:@"-" withString:@""];
        record.yearMonth = [yearMonth integerValue];
        NSString* dateShow = [YWCommonTool showTime:record.readingTime / 1000 andFormatter:KTimeFormatShortDateTime];
        record.dateShow = dateShow;
        record.yearMonthDay = [YWCommonTool showTime:record.readingTime / 1000 andFormatter:KTimeFormatDate];
        record.equipmentId = record.equipment.equipmentId;
        YWEquipment *equipment = [[YWEquipmentManager shareManager]equipmentWithId:record.equipmentId];
        record.equipmentTypeId = equipment.equipmentTypeId;
    }];
    isSave = [[YWMeterReadingDBManager shareManager] updateNetWorkMeterReadingRecordWithRecordArray:records];
    return isSave;
}

- (void)modifyThisReadNumberOfMeterReadingRecord:(YWMeterReadingRecord*)record withBlock:(void (^)(BOOL success))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    NSDictionary *params = @{@"meterRecordId":record.meterRecordId,@"reading":@(record.thisReadNumber),@"note":record.note};
    NSString *url = [YWCommonTool modityMyMeterReadingRecordUrl];
    YWLog(@"修改抄表读数url:%@,parmas:%@",url,params);
    
    [[WMHttpTool shareHttpTool] putWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        BOOL save = [[YWMeterReadingDBManager shareManager] modifyReadNumberOfMeterReadingRecord:record];
        if (save) {
            //[[NSNotificationCenter defaultCenter] postNotificationName:KPostModifyMeterReadingRecordSuccessNoti object:nil];
        }
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        
    }];
}

- (void)requestUnReadMeterArrayWithPage:(NSInteger)page equipmentTypeCode:(NSString*)equipmentTypeCode buildingId:(NSString*)buildingId apartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId meterChargeTypeId:(NSInteger)chargeTypeId complete:(void (^)(NSArray *meterArray))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@(page) forKey:@"page"];
    [params setValue:@(10) forKey:@"pageSize"];
    [params setValue:equipmentTypeCode?:@"" forKey:@"equipmentTypeOwnCode"];
    [params setValue:buildingId?:@"" forKey:@"buildingId"];
    if (apartmentId>0) {
        [params setValue:@(apartmentId) forKey:@"apartmentId"];
    }
    if (floorId>0) {
        [params setValue:@(floorId) forKey:@"floorId"];
    }
    if (locationId>0) {
        [params setValue:@(locationId) forKey:@"locationId"];
    }
    if (chargeTypeId>0) {
        [params setValue:@(chargeTypeId) forKey:@"priceType"];
    }
    YWLog(@"%@",params);
    NSString * url = [YWCommonTool getThisMonthUnreadMeterEquipmentUrl];
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* meterArray = [YWEquipment mj_objectArrayWithKeyValuesArray:json];
        if (complete) {
            complete(meterArray);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:@"查询失败,请稍后再试!"];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
- (void)requestHaveReadMeterArrayWithPage:(NSInteger)page equipmentTypeCode:(NSString*)equipmentTypeCode buildingId:(NSString*)buildingId apartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId meterChargeTypeId:(NSInteger)chargeTypeId complete:(void (^)(NSArray *meterArray))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@(page) forKey:@"page"];
    [params setValue:@(10) forKey:@"pageSize"];
    [params setValue:equipmentTypeCode?:@"" forKey:@"equipmentTypeOwnCode"];
    [params setValue:buildingId?:@"" forKey:@"buildingId"];
    if (apartmentId>0) {
        [params setValue:@(apartmentId) forKey:@"apartmentId"];
    }
    if (floorId>0) {
        [params setValue:@(floorId) forKey:@"floorId"];
    }
    if (locationId>0) {
        [params setValue:@(locationId) forKey:@"locationId"];
    }
    if (chargeTypeId>0) {
        [params setValue:@(chargeTypeId) forKey:@"priceType"];
    }
    YWLog(@"%@",params);
    NSString * url = [YWCommonTool getThisMonthReadMeterEquArrayUrl];
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* meterArray = [YWEquipment mj_objectArrayWithKeyValuesArray:json];
        if (complete) {
            complete(meterArray);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:@"查询失败,请稍后再试!"];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
@end
